package com.xoa.service.task.impl;


import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.task.TaskManageMapper;
import com.xoa.dao.task.TaskTypeMapper;
import com.xoa.dao.task.TaskUserMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.department.Department;
import com.xoa.model.hr.HrphotoWithBLOBs;
import com.xoa.model.task.TaskManage;
import com.xoa.model.task.TaskType;
import com.xoa.model.task.TaskUser;
import com.xoa.model.users.Users;
import com.xoa.service.task.TaskSubordinateService;
import com.xoa.service.task.TaskTypeService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class TaskSubordinaeServiceImpl implements TaskSubordinateService {

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private TaskUserMapper taskUserMapper;

    @Resource
    private TaskManageMapper taskManageMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Override
    public ToJson querySubordinate(HttpServletRequest request) {
        ToJson toJson = new ToJson();
        try {
            List<Users> usersList = new ArrayList<>();
            List deptIdList = new ArrayList<>();
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            Map map = new HashMap();
            map.put("userPriv", users.getUserPriv());
            List<Department> departments = departmentMapper.getChildDepart(users.getDeptId());
            for (Department department : departments) {
                List list = getdepartmentChil(department.getDeptId());
                for (int i = 0; i < list.size(); i++) {
                    deptIdList.add(list.get(i));
                }
            }
            if(deptIdList.size()>0){
                map.put("deptIds", deptIdList);
            }else{
                toJson.setFlag(0);
                return toJson;
            }
            usersList = usersMapper.querySubordinate(map);
            // usersMapper
            toJson.setObj(usersList);
            toJson.setFlag(0);
            toJson.setMsg("success");
        } catch (Exception e) {
            toJson.setFlag(1);
            toJson.setMsg("erro");
            e.printStackTrace();
        }
        return toJson;
    }

    @Override
    public ToJson querySubordinateTask(HttpServletResponse response, HttpServletRequest request,String userId ,Integer deptId , Integer pageSize, Integer page, Boolean useFlag, int temp) {
        ToJson toJson = new ToJson();
        try {
            List<TaskManage> taskManages = new ArrayList<>();
            List<TaskManage> taskManages1 = new ArrayList<>();
            List<Users> usersList = new ArrayList<>();
            List deptIdList = new ArrayList<>();
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            Map maptemp = new HashMap();
            maptemp.put("userPriv", users.getUserPriv());
            List<Department> departments = departmentMapper.getChildDepart(deptId != null ? deptId:users.getDeptId());
            for (Department department : departments) {
                List list = getdepartmentChil(department.getDeptId());
                for (int i = 0; i < list.size(); i++) {
                    deptIdList.add(list.get(i));
                }
            }
            if(deptId != null){
                deptIdList.add(deptId);
            }
            maptemp.put("deptIds", deptIdList);
            String[] userList ;
            if (!StringUtils.checkNull(userId)) {
                userList = new String[1];
                userList[0] = userId;
            } else {
                usersList = usersMapper.querySubordinate(maptemp);
                userList = new String[usersList.size()];
                for (int i = 0; i < usersList.size(); i++) {
                    userList[i] = usersList.get(i).getUserId();
                }
            }
            PageParams pages = new PageParams();
            pages.setPage(page);
            pages.setPageSize(pageSize);
            pages.setUseFlag(true);
            Map map = new HashMap();
            map.put("userIds", userList);
            if (userList.length != 0) {
                taskManages1 = taskManageMapper.querySubordinateTaskByUserId(map);
                map.put("page", pages);
                taskManages = taskManageMapper.querySubordinateTaskByUserId(map);
                for (TaskManage taskManage : taskManages) {
                    Map mapTemp = new HashMap();
                    mapTemp.put("userId", users.getUserId());
                    mapTemp.put("taskRelation", "2");
                    mapTemp.put("taskId", taskManage.getTaskId());
                    List<TaskUser> taskUsers = taskUserMapper.queryTaskUserIdByTaskId(mapTemp);
                    if (taskUsers.size() > 0) {
                        taskManage.setFollow(1);
                    }
                    List<TaskManage> taskManageList = taskManageMapper.queryChildTaskManage(taskManage.getTaskId());
                    taskManage.setTaskManages(taskManageList);
                    if (taskManageList.size() == 0) {
                        taskManage.setTaskManageCount("0/0");
                    } else {
                        taskManage.setTaskManageCount(taskManageList.size() + "/" + taskManageList.size());
                    }
                    if ("0".equals(taskManage.getTaskStatus())) {//进行中
                        taskManage.setImportantLevelStr("进行中");
                    } else {
                        taskManage.setImportantLevelStr("已完成");
                    }
                    taskManage.setManageUserName(usersMapper.getUsernameByUserId(taskManage.getManageUser()));
                }
            }
            //根据下属id查询所参与、关注、分享的任务

           /* List<TaskUser>taskUsers = taskUserMapper.queryTaskUserIdByTaskId(map);
            for(TaskUser taskUser:taskUsers){
                taskManages.add(taskManageMapper.queryTaskManageByTaskId(taskUser.getTaskId()));
            }*/
            if (temp != 0) {//导出
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String dateStr = sdf.format(date);
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("下属任务", 7);
                String[] secondTitles = {"任务名称", "负责人", "评分", "子任务", "结束日期", "进度", "完成情况"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                String[] beanProperty = {"taskName", "manageUser", "taskGrade", "taskManageCount", "endDate", "progress", "importantLevelStr"};
                SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, taskManages, beanProperty);
                ServletOutputStream out = response.getOutputStream();
                String filename = "下属任务" + dateStr + ".xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }
            toJson.setObj(taskManages);
            toJson.setTotleNum(taskManages1.size());
            toJson.setMsg("success");
            toJson.setFlag(0);
        } catch (Exception e) {
            toJson.setMsg("erro");
            toJson.setFlag(1);
            e.printStackTrace();
        }
        return toJson;
    }

    public List getdepartmentChil(int deptId) {
        List list = new ArrayList();
        list.add(deptId);
        List<Department> departments = departmentMapper.getChildDepart(deptId);
        for (Department department : departments) {
            list.add(department.getDeptId());
            if (departments.size() != 0) {
                getdepartmentChil(department.getDeptId());
            } else {
                return list;
            }
        }
        return list;
    }


    @Override
    public ToJson batchattentionTask(HttpServletRequest request, String taskId) {
        ToJson toJson = new ToJson();
        try {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            TaskUser taskUser = new TaskUser();
            taskUser.setUserId(users.getUserId());
            taskUser.setTaskRelation("2");
            if (!StringUtils.checkNull(taskId)) {
                String[] taskIdArray = taskId.split(",");
                for (String s : taskIdArray) {
                    taskUser.setTaskId(Integer.valueOf(s));
                    taskUserMapper.addTaskUser(taskUser);
                }
                toJson.setMsg("success");
                toJson.setFlag(0);
            }
        } catch (Exception e) {
            toJson.setFlag(1);
            toJson.setMsg("erro");
            e.printStackTrace();
        }
        return toJson;
    }
}
